// src/logger/context/request-context.middleware.ts
import { randomUUID } from "node:crypto";

import { Injectable, NestMiddleware } from "@nestjs/common";
import { ClsService } from "nestjs-cls";
import { REQUEST_ID_KEY } from "../constant/global-enum";
/**
 * 请求上下文中间件
 * 用于为每个请求生成唯一的请求 ID，并挂载到 req 对象上
 */
@Injectable()
export class RequestContextMiddleware implements NestMiddleware {
    constructor(private readonly cls: ClsService) {}

    use(req: any, res: any, next: () => void) {
        const reqId = randomUUID();
        // this.cls.set("reqId", reqId);
        // req.id = reqId; // 可选：挂载到 req 对象
        // next();
        this.cls.run(() => {
            this.cls.set(REQUEST_ID_KEY, reqId); // 安全设置
            req.id = reqId; // 挂载到 req，方便非 CLS 场景使用
            next(); // ⚠️ 必须在 run 里面调用 next，确保后续处理在同一个上下文
        });
    }
}
